package com.ap2;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.ap2.pegaMusica.Musica;

public class Ap2SextaActivity extends Activity {

	static Spinner sp;
	MediaPlayer mediaPlayer = new MediaPlayer();
	ImageButton play, stop, download;
	int a = 0, b = 0, r;
	static String radio = null;
	List<Musica> musicas;
	Musica musica = new Musica();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		play = (ImageButton) findViewById(R.id.play);
		stop = (ImageButton) findViewById(R.id.stop);
		download = (ImageButton) findViewById(R.id.download);

		sp = (Spinner) findViewById(R.id.radios);
		ArrayAdapter<String> ar = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getRadios());
		ar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp.setAdapter(ar);

		play.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (a == 0) {
					starta();
					r = sp.getSelectedItemPosition();
					radio = getLink(r);
					Log.i("IF", "INICIO");
					Log.i("radio", "link..." + radio);
					Log.i("NUMEROOO", "selecionado..." + r);
					mediaPlayer.prepareAsync();
					play.setImageResource(R.drawable.ic_tab_play_selected);
					a = 1;
					Log.i("IF", "FIM");
				} else if (b == 0) {
					Log.i("pause", "Pausada...");
					mediaPlayer.pause();
					play.setImageResource(R.drawable.ic_tab_pause_selected);
					b = 1;
				} else {
					mediaPlayer.start();
					Log.i("buffer", "Continuando...");
					play.setImageResource(R.drawable.ic_tab_play_pause_selected);
					b = 0;
				}

			}
		});

		stop.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mediaPlayer.stop();
				mediaPlayer.reset();
				Log.i("Stop", "STOPADO!");
				play.setImageResource(R.drawable.ic_tab_play_unselected);
				a = b = 0;

			}
		});

		download.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// mensagenBar();

				try {

					new DownAsync().execute();

					/*
					 * musicas = PesquisaBaixa.buscarMusicaTocada(radio);
					 * 
					 * musica = musicas.get(0); mensagem("Tocando",
					 * "Nome Anime: " + musica.getAnime() +" Musica: " +
					 * musica.getTitulo() + " id: " + musica.getLink());
					 * 
					 * PesquisaBaixa.baixarMusica(musica);
					 */

					// mensagem("Down", "Concluido. ");

					// musicas = buscarMusicaTocada();
					// if (musicas.get(0) == null) {
					// mensagem("Musica", "Não Tem a musica.");
					// }else {
					// musica = musicas.get(0);
					// mensagem("Tocando", "Nome Anime: " + musica.getAnime()
					// +" Musica: " + musica.getTitulo() + " id: " +
					// musica.getLink());
					//
					// mensagenBar();
					// baixarMusica(musica);
					// mensagem("Tocando", "baixando.... ");
					// }

				} catch (Exception e) {
					mensagem("Down", "Não foi possivel baixar. " + e.toString());
					e.printStackTrace();
				}

			}
		});

	}

	private static final int HELLO_ID = 1;

	public void mensagenBar() {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		int icon = R.drawable.download_black;
		CharSequence tickerText = "Hello";
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);

		Context context = getApplicationContext();
		CharSequence contentTitle = "Baixando";
		CharSequence contentText = "Baixando...";
		Intent notificationIntent = new Intent(this, Ap2SextaActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent);

		mNotificationManager.notify(HELLO_ID, notification);
		mNotificationManager.cancelAll();
	}

	public void starta() {
		try {

			r = sp.getSelectedItemPosition();
			Log.i("NUMEROOO", "selecionado..." + r);
			Log.i("radio", "link..." + radio);

			mediaPlayer.setDataSource(getLink(r));
			mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					mediaPlayer.start();
				}
			});
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getLink(int selecR) {
		switch (selecR) {
		case 0:
			return "http://ouvir.radioblast.com.br:8000";
		case 1:
			return "http://70.36.100.78:9566";
		case 2:
			return "http://radioanimix.no-ip.org:8068";
		default:
			break;
		}
		return null;

	}

	public void mensagem(String titulo, String texto) {
		AlertDialog.Builder men = new AlertDialog.Builder(Ap2SextaActivity.this);
		men.setTitle(titulo);
		men.setMessage(texto);
		men.setNeutralButton("ok", null);
		men.show();
	}

	public static String[] getRadios() {
		String[] radio = new String[] { "Blast", "J-Hero", "Animix" };
		return radio;

	}

	public static String[] getListMuz(List<Musica> ist) {
		String[] radio = new String[ist.size()];
		for (int i = 0; i < radio.length || i < 6; i++) {
			radio[i] = ist.get(i).getTitulo();
		}
		return radio;

	}

	// ------------------------------------------............................................----------------------------------------------------------------

	private static DefaultHttpClient httpclient = null;

	public static URI uri = null;

	public static DefaultHttpClient getHttpclient() {
		if (httpclient == null) {
			httpclient = new DefaultHttpClient();
		}
		return httpclient;
	}

	public static boolean hasLogado() throws Exception {
		String html = EntityUtils.toString(getHttpclient().execute(
				new HttpGet(getUri())).getEntity());
		if (!html.contains("frmLogar")) {
			return true;
		}
		return false;
	}

	public static List<Musica> buscarMusica(String desc) throws Exception {

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("textBusca", desc));
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
				"UTF-8");

		HttpPost post = new HttpPost(
				"http://www.mp3.animaniaclub.com.br/buscar/");
		post.setEntity(entity);
		HttpResponse responseResult = getHttpclient().execute(post);
		HttpEntity enti = responseResult.getEntity();

		List<Musica> musicas = new ArrayList<Musica>();

		try {
			String html = EntityUtils.toString(enti);
			if (!html.contains("tbMusicas")) {
				return musicas;
			}
			String[] htmlArray = html.split("id=\"tbMusicas\"");

			htmlArray[1] = htmlArray[1].substring(0,
					htmlArray[1].indexOf("</table>"));
			while (htmlArray[1].contains("<tr")
					&& htmlArray[1].contains("</tr>")) {
				musicas.add(populate(getNextTR(htmlArray[1])));
				htmlArray[1] = htmlArray[1].substring(htmlArray[1].indexOf(">",
						htmlArray[1].indexOf("<tr")));
			}
		} catch (Exception e) {
			System.out.println("teste");
		}

		return musicas;
	}

	public static void logar() throws Exception {
		System.out.println("logando...");
		List<NameValuePair> formLoginParams = new ArrayList<NameValuePair>();
		formLoginParams.add(new BasicNameValuePair("txtLogin",
				"joerlan-joe@hotmail.com"));
		formLoginParams.add(new BasicNameValuePair("txtSenha", "021091"));
		formLoginParams.add(new BasicNameValuePair("act", "in"));
		formLoginParams.add(new BasicNameValuePair("paginaAtual", "/"));
		formLoginParams.add(new BasicNameValuePair("btLogar", "Logar"));
		UrlEncodedFormEntity entityLogin = new UrlEncodedFormEntity(
				formLoginParams, "utf-8");

		HttpPost login = new HttpPost(
				"http://www.mp3.animaniaclub.com.br/sql2.php");
		login.setEntity(entityLogin);
		HttpResponse response = getHttpclient().execute(login);
		EntityUtils.getContentCharSet(response.getEntity());
		// EntityUtils.consume(response.getEntity());

		if (hasLogado()) {
			System.out.println("logado");
		} else {
			System.out.println("falha no login");
		}
		;
	}

	public static void baixarMusica(Musica musica) throws Exception {
		if (!hasLogado()) {
			logar();
			// Toast .makeText(null, "logado", Toast.LENGTH_LONG).show();
		} else {
			// Toast .makeText(null, "erro ao logar", Toast.LENGTH_LONG).show();
			System.out.println("logado");
		}

		HttpGet get = new HttpGet(
				"http://www.mp3.animaniaclub.com.br/downMp3.php?idcliques="
						+ musica.getLink());
		HttpEntity response = null;
		try {
			response = getHttpclient().execute(get).getEntity();
		} catch (Exception e) {
			System.out.println("Não logado para baixar");
			e.printStackTrace();
		}

		OutputStream out;
		try {
			out = new FileOutputStream(
					Environment.getExternalStorageDirectory() + "/Download/"
							+ musica.getLink() + ".rar");
			response.writeTo(out);
		} catch (Exception e) {
			System.out.println("Não foi possivel gravar");
			e.printStackTrace();
		}

		// return new File("/Android/data/files/" + musica.getLink() + ".rar");

	}

	public static String getNextTR(String html) {
		return html.substring(html.indexOf(">", html.indexOf("<tr")),
				html.indexOf("</tr>", html.indexOf(">", html.indexOf("<tr"))));
	}

	public static String getValueNextTD(String tr) {
		return tr.substring(tr.indexOf(">", tr.indexOf("<td")) + 1,
				tr.indexOf("</td>", tr.indexOf(">", tr.indexOf("<td"))));
	}

	public static Musica populate(String tr) {
		Musica musica = new Musica();
		musica.setAnime(getValueNextTD(tr).replace("<b>", "").replace("</b>",
				""));
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		musica.setTitulo(getValueNextTD(tr).replace("<b>", "").replace("</b>",
				""));
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		musica.setAutor(getValueNextTD(tr));
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		musica.setTipo(getValueNextTD(tr));
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		musica.setTamanho(getValueNextTD(tr));
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		musica.setTempo(getValueNextTD(tr));
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		musica.setClicks(getValueNextTD(tr));
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		musica.setLink(getValueNextTD(tr).substring(
				getValueNextTD(tr).indexOf("download-mp3/") + 13,
				getValueNextTD(tr).indexOf("/",
						getValueNextTD(tr).indexOf("download-mp3/") + 13)));
		return musica;
	};

	public static URI getUri() throws URISyntaxException {
		if (uri == null) {
			uri = new URI("http://www.mp3.animaniaclub.com.br");
		}
		return uri;
	}

	public static List<Musica> buscarMusicaTocada() throws Exception {

		URL url = new URL(radio + "/played.html");
		URLConnection yc = url.openConnection();
		yc.setRequestProperty(
				"User-Agent",
				"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
		BufferedReader in = new BufferedReader(new InputStreamReader(
				yc.getInputStream()));
		String inputLine;
		String string = "";
		while ((inputLine = in.readLine()) != null)
			string = string + inputLine;
		in.close();

		List<String> musicas = getDsMusica(string);
		List<List<Musica>> dados = new ArrayList<List<Musica>>();
		// buscando musica pela descriçao obtida
		String[] buscas = musicas.get(0).split(" - ");

		for (int i = 0; i < buscas.length; i++) {
			// removendo o (***)
			if (buscas[i].contains("(")) {
				buscas[i] = buscas[i].substring(0, buscas[i].indexOf("("));
			}
			// removendo o =***=
			if (buscas[i].contains("=")) {
				buscas[i] = buscas[i].substring(0, buscas[i].indexOf("="));
			}
			// removendo os espaços
			if (buscas[i].endsWith(" ")) {
				buscas[i] = buscas[i].substring(0, buscas[i].length() - 1);
			}
			if (buscas[i].startsWith(" ")) {
				buscas[i] = buscas[i].substring(1, buscas[i].length());
			}
		}
		for (int i = 0; i < buscas.length; i++) {
			List<Musica> list = new ArrayList<Musica>();
			if (buscas[i].length() >= 3) {
				list = buscarMusica(buscas[i]);
			}

			if (list.size() == 1) {
				return list;
			} else if (list.size() != 0) {
				dados.add(list);
			}
		}

		if (dados.size() == 1) {
			return dados.get(0);
		}

		List<Musica> cruzamento = new ArrayList<Musica>();
		for (int i = 0; i < dados.size() - 1; i++) {
			for (int j = 0; j < dados.get(i).size(); j++) {
				for (int j2 = 0; j2 < dados.get(i + 1).size(); j2++) {
					if (dados.get(i).get(j).getLink()
							.equals(dados.get(i + 1).get(j2).getLink())) {
						cruzamento.add(dados.get(i).get(j));
					}
				}
			}
		}
		if (cruzamento.size() == 0 && dados.size() > 0) {
			List<Musica> list = new ArrayList<Musica>();
			list = dados.get(0);
			for (List<Musica> list2 : dados) {
				if (list.size() > list2.size()) {
					list = list2;
				}
			}
		}

		return cruzamento;
	}

	private static List<String> getDsMusica(String html) {
		String temp = html.split("Song Title")[1];
		temp = temp.split("</table>")[0];
		String tr;
		List<String> strings = new ArrayList<String>();

		// fix por causa da primeira musica q tem uma coluna a mais

		tr = getNextTR(temp);
		tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
		strings.add(tr.substring(tr.indexOf(">", tr.indexOf("<td")) + 1,
				tr.indexOf("<td>", tr.indexOf(">", tr.indexOf("<td")))));
		temp = temp.substring(temp.indexOf(">", temp.indexOf("<tr")));

		// end fix

		while (temp.contains("<tr") && temp.contains("</tr>")) {
			tr = getNextTR(temp);
			tr = tr.substring(tr.indexOf(">", tr.indexOf("<td")));
			strings.add(tr.substring(tr.indexOf(">", tr.indexOf("<td")) + 1,
					tr.length()));
			temp = temp.substring(temp.indexOf(">", temp.indexOf("<tr")));

		}

		System.out.println(strings.get(0));
		return strings;
	}

	class DownAsync extends AsyncTask<String, Void, String> {

		private ProgressDialog progressDialog;

		protected void onPreExecute() {
			progressDialog = new ProgressDialog(Ap2SextaActivity.this);

			progressDialog.setMessage("Pesquisando...");
			progressDialog.show();
		}

		protected String doInBackground(String... v) {

			try {
				Log.i("vai", "PESQUISANDO");
				musicas = buscarMusicaTocada();
				Log.i("vai", "PESQUISADO!!!!!!!!!!!");
				musica = musicas.get(0);
				Log.i("vai", "COMEÇAR A BAIXAR");
				baixarMusica(musica);
				Log.i("vai", "BAIXOU!!!");
			} catch (Exception e) {
				progressDialog.dismiss();
				mensagem("Down", "Falha ao baixar...-> " + musica.getTitulo()+" - Erro: " + e.toString());
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			mensagem("Down Concluido", "Salvo com o nome "+ musica.getLink());
		}
	}

}